package com.kpmg.datalake.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-08-17 21:45:55
 */
public class HttpUtils {

  private HttpUtils() {
  }

  /**
   * 发送get 请求
   *
   * @param url 参数 url
   * @return 返回结果值
   */
  public static String httpGet(String url) {
    return httpGet(url, new HashMap<>(2));

  }

  /**
   * 发送get 请求
   *
   * @param url 参数 url
   * @param params 请求参数
   * @return 返回结果值
   */
  public static String httpGet(String url, Map<String, String> params) {
    List<NameValuePair> paramsList = Lists.newArrayList();
    if (!CollectionUtils.isEmpty(params)) {
      for (Entry<String, String> entry : params.entrySet()) {
        paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
    }
    return httpGet(url, paramsList);
  }

  /**
   * 发送get 请求
   *
   * @param url 参数 url
   * @param params 请求参数
   * @return 返回结果值
   */
  public static String httpGet(String url, List<NameValuePair> params) {
    CloseableHttpResponse httpResponse = null;
    try {
      try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        if (!CollectionUtils.isEmpty(params)) {
          String paramString = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
          url = url.contains("?") ? (url + "&" + paramString) : (url + "?" + paramString);
        }
        HttpGet httpGet = new HttpGet(url);
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60 * 1000)
            .setSocketTimeout(60 * 1000).setConnectTimeout(60 * 1000).build();
        httpGet.setConfig(requestConfig);
        httpResponse = httpClient.execute(httpGet);
      }
      if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
          return EntityUtils.toString(entity);
        }
      }
    } catch (IOException e) {
      LogUtils.error(e.getMessage());
    } finally {
      if (httpResponse != null) {
        try {
          httpResponse.close();
        } catch (IOException e) {
          //nothing to do
        }
      }
    }
    return null;
  }

  /**
   * 发送 post json格式请求
   *
   * @param url url路径
   * @param params 请求参数
   * @return 结果
   */

  public static String httpPostJson(String url, Map<String, Object> params) {
    return httpPostJson(url, JSONObject.toJSONString(params));
  }

  /**
   * 发送 post json格式请求
   * @param url url路径
   * @param params 请求参数
   * @return 结果
   */
  public static String httpPostJson(String url, String params) {
    CloseableHttpResponse httpResponse = null;
    try {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(url);
      //设置请求和传输超时时间
      RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60 * 1000)
          .setSocketTimeout(60 * 1000).setConnectTimeout(60 * 1000).build();
      httpPost.setConfig(requestConfig);
      StringEntity entity = new StringEntity(params, Consts.UTF_8);
      entity.setContentEncoding(Consts.UTF_8.toString());
      entity.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
      httpPost.setEntity(entity);
      httpResponse = httpClient.execute(httpPost);
      if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
          return EntityUtils.toString(httpEntity);
        }
      }
    } catch (IOException e) {
      LogUtils.error(e.getMessage());
    } finally {
      if (httpResponse != null) {
        try {
          httpResponse.close();
        } catch (IOException e) {
          //nothing to do
        }
      }
    }
    return null;
  }

}
